package com.business.user.listener;

import com.alibaba.fastjson.JSONObject;
import com.business.common.enums.RabbitMqConstant;
import com.business.redis.ExpiresTimeEnum;
import com.business.redis.constant.RedisKeyConstant;
import com.business.redis.utils.RedisUtil;
import com.business.user.service.SmsService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 监听发送短信
 */
@Service
public class SmsListener {
    private Logger logger = LoggerFactory.getLogger(SmsListener.class);

    @Autowired
    private SmsService smsService;

    /**
     * 监听 发送验证码队列
     *
     * @param message
     * @param channel
     */
    @RabbitListener(queues = RabbitMqConstant.SEND_VERIFICATION_CODE)
    public void sendVerificationCodeListener(Message message, Channel channel) throws IOException {
        JSONObject params = JSONObject.parseObject(new String(message.getBody()));
        logger.info(RabbitMqConstant.SEND_VERIFICATION_CODE + " 接收参数执行开始,参数： " + params);
        if (null == params) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        String phone = params.getString("phone");
        try {
            String key = String.format(RedisKeyConstant.USER_GET_VERIFICATION_CODE, phone);
            if (!RedisUtil.hasKey(key)) {
                String r = smsService.sendVerificationCode(phone);
                // 将验证码缓存到redis
                RedisUtil.setValue(key, r, ExpiresTimeEnum.VALIDATE_CODE.getExpiresTime());
            }
            logger.info(RabbitMqConstant.SEND_VERIFICATION_CODE + " 执行结束");
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

    /**
     * 监听 发送短信队列
     *
     * @param message
     * @param channel
     */
    @RabbitListener(queues = RabbitMqConstant.SMS)
    public void sendSms(Message message, Channel channel) throws IOException {
        JSONObject params = JSONObject.parseObject(new String(message.getBody()));
        logger.info(RabbitMqConstant.SMS + " 接收参数执行开始,参数： " + params);
        if (null == params) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        String phone = params.getString("phone");
        String templateCode = params.getString("templateCode");
        String username = params.getString("username");
        String dateTime = params.getString("dateTime");
        try {
            smsService.send(phone, username, dateTime, templateCode);
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

}
